package cn.itcast.erp.service.impl;

import cn.itcast.erp.dao.mapper.CStoreDetailMapper;
import cn.itcast.erp.dao.mapper.CStoreoperMapper;
import cn.itcast.erp.dao.mapper.EmpMapper;
import cn.itcast.erp.dao.mapper.InventoryMapper;
import cn.itcast.erp.entity.Goodstype;
import cn.itcast.erp.entity.Inventory;
import cn.itcast.erp.entity.Storedetail;
import cn.itcast.erp.entity.Storeoper;
import cn.itcast.erp.entity.utils.AjaxResult;
import cn.itcast.erp.entity.utils.DateUtils;
import cn.itcast.erp.service.CStoreDetailService;
import cn.itcast.erp.service.InventoryService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service("inventoryService")
public class InventoryServiceImpl implements InventoryService {

    @Resource
    private InventoryMapper inventoryMapper;

    @Resource
    private CStoreDetailMapper storeDetailMapper;

    @Resource
    private CStoreoperMapper storeoperMapper;


    //查询记录
    @Override
    public AjaxResult findInventory(Inventory inventory) {

        AjaxResult ar = new AjaxResult();
        int total = inventoryMapper.count();
        List <Inventory> list = inventoryMapper.findInventory(inventory);
        ar.setTotal(total);
        ar.setRows(list);
        return ar;
    }

    @Override
    public Inventory findInventoryById(Long uuid) {
        return this.inventoryMapper.findInventoryById(uuid);
    }


    //判断库存,新增记录
    @Override
    public AjaxResult insertInventory(Long userId, Inventory inventory) {

        AjaxResult ar = new AjaxResult();
        String msg;
        //当前用户
        inventory.setCreater(userId);
        //生成createtime
        inventory.setCreatetime(DateUtils.now());
        //state=未审核
        inventory.setState("0");
        if ("0".equals(inventory.getType())) {
            Storedetail store =
                    this.storeDetailMapper.findOneDetail(inventory.getStoreuuid(), inventory.getGoodsuuid());
            if (store != null) {
                if (store.getNum() > inventory.getNum()) {
                    int result = this.inventoryMapper.insertInventory(inventory);
                    if (result == 1) {
                        msg = "添加成功";
                    } else {
                        msg = "添加失败";
                    }
                } else {
                    msg = "添加失败:盘点数量超过库存数量";
                }
            } else {
                msg = "添加失败:盘点数量超过库存数量";
            }
        } else if ("1".equals(inventory.getType())) {
            int result = this.inventoryMapper.insertInventory(inventory);
            if (result == 1) {
                msg = "添加成功";
            } else {
                msg = "添加失败";
            }
        } else {
            msg = "数据异常";
        }
        ar.setMsg(msg);
        return ar;
    }


    //更新记录
    @Override
    public AjaxResult updateInventory(Inventory inventory) {
        AjaxResult ar = new AjaxResult();
        String msg;
        if ("0".equals(inventory.getType())) {
            Storedetail store =
                    this.storeDetailMapper.findOneDetail(inventory.getStoreuuid(), inventory.getGoodsuuid());
            if (store != null) {
                if (store.getNum() > inventory.getNum()) {
                    int result = this.inventoryMapper.updateInventory(inventory);
                    if (result == 1) {
                        msg = "修改成功";
                    } else {
                        msg = "修改失败";
                    }
                } else {
                    msg = "修改失败:盘点数量超过库存数量";
                }
            } else {
                msg = "修改失败:盘点数量超过库存数量";
            }
        } else if ("1".equals(inventory.getType())) {
            int result = this.inventoryMapper.updateInventory(inventory);
            if (result == 1) {
                msg = "修改成功";
            } else {
                msg = "修改失败";
            }
        } else {
            msg = "数据异常";
        }
        ar.setMsg(msg);
        return ar;
    }


    //删除记录
    @Override
    public int deleteInventory(Long uuid) {
        if (uuid != null) {
            int i = this.inventoryMapper.deleteInventory(uuid);
            return i;
        }
        return -1;
    }


    //审核记录,更新库存
    @Transactional
    @Override
    public AjaxResult updateState(Long userId, Long uuid) {

        AjaxResult ar = new AjaxResult();
        String msg;
        //判断审核者权限

        //修改审核状态
        int state = this.inventoryMapper.updateState(userId, uuid, DateUtils.now());

        //更新库存
        int storeNum = 0;
        int storeInsert = 0;
        Inventory inventory = this.inventoryMapper.findInventoryById(uuid);

        //盘亏时数量为负
        if ("0".equals(inventory.getType())) {
            inventory.setNum(inventory.getNum() * (-1));
            storeNum = this.storeDetailMapper.updateStoreNum(inventory);

            //判断盘盈时库存是否有该商品
        } else if ("1".equals(inventory.getType())) {
            Storedetail store
                    = this.storeDetailMapper.findOneDetail(inventory.getStoreuuid(), inventory.getGoodsuuid());
            if (store == null) {
                Storedetail storedetail = new Storedetail();
                storedetail.setGoodsuuid(inventory.getGoodsuuid());
                storedetail.setStoreuuid(inventory.getStoreuuid());
                storedetail.setNum(inventory.getNum());
                storeInsert = this.storeDetailMapper.insertOne(storedetail);
            } else {
                storeNum = this.storeDetailMapper.updateStoreNum(inventory);
            }
        }

        //添加库存变更记录
        Storeoper storeoper = new Storeoper();
        storeoper.setEmpuuid(userId);
        storeoper.setOpertime(DateUtils.now());
        storeoper.setGoodsuuid(inventory.getGoodsuuid());
        storeoper.setStoreuuid(inventory.getStoreuuid());
        storeoper.setNum(inventory.getNum());
        //1.入库(1.盘盈) 2.出库(0.盘亏)
        if ("1".equals(inventory.getType())) {
            storeoper.setType("1");
        } else if ("0".equals(inventory.getType())) {
            storeoper.setType("2");
        }
        int record = this.storeoperMapper.insertOne(storeoper);


        if (state == 1 && (storeNum == 1 || storeInsert == 1) && record == 1) {
            msg = "审核成功,库存已更新";
        } else {
            msg = "审核失败";
        }
        ar.setMsg(msg);
        return ar;
    }

    // 导出Excel
    @Override
    public InputStream getAllInventoryEx() {
        //添加数据
        List <Inventory> inventory = inventoryMapper.getAllInventoryEx();

        HSSFWorkbook sheets = new HSSFWorkbook();  // 定义一个新的工作簿
        Sheet sheet = sheets.createSheet("盘盈盘亏信息");  // 创建第一个新的Sheet页
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        //创建第一行（也可以成为表头）
        Row row1 = sheet.createRow(0);
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 20 * 256);
        sheet.setColumnWidth(3, 30 * 256);
        sheet.setColumnWidth(4, 20 * 256);
        sheet.setColumnWidth(5, 30 * 256);
        sheet.setColumnWidth(6, 20 * 256);
        sheet.setColumnWidth(7, 30 * 256);
        sheet.setColumnWidth(8, 30 * 256);
        sheet.setColumnWidth(9, 20 * 256);
        sheet.setColumnWidth(10, 30 * 256);

        //给表头第一行一次创建单元格
        String[] headers = {"编号","商品","仓库","数量","类型","登记日期","审核日期","登记人","审核人","状态","备注"};
        for(int i = 0; i < headers.length; i++){
            row1.createCell(i).setCellValue(headers[i]);
            row1.setHeightInPoints(30);//设置行的高度是30
        }



        //向单元格里添加数据
        for (short i = 0; i < inventory.size(); i++) {
            row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(inventory.get(i).getUuid());
            row1.createCell(1).setCellValue(inventory.get(i).getGoodsName());
            row1.createCell(2).setCellValue(inventory.get(i).getStoreName());
            row1.createCell(3).setCellValue(inventory.get(i).getNum());
            if (inventory.get(i).getType().equals("0")) {
                row1.createCell(4).setCellValue("盘亏");
            } else if (inventory.get(i).getType().equals("1")) {
                row1.createCell(4).setCellValue("盘盈");
            }
            row1.createCell(5).setCellValue(sdf.format(inventory.get(i).getCreatetime()));
            row1.createCell(6).setCellValue(sdf.format(inventory.get(i).getChecktime()));
            row1.createCell(7).setCellValue(inventory.get(i).getCreaterName());
            row1.createCell(8).setCellValue(inventory.get(i).getCheckerName());
            if (inventory.get(i).getState().equals("0")) {
                row1.createCell(9).setCellValue("未审核");
            } else if (inventory.get(i).getState().equals("1")) {
                row1.createCell(9).setCellValue("已审核");
            }
            row1.createCell(10).setCellValue(inventory.get(i).getRemark());
            row1.setHeightInPoints(30);//设置行的高度是30
        }
        //字节流缓存区
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        try {
            sheets.write(bo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ByteArrayInputStream(bo.toByteArray());
    }
}
